package com.sailors.common.task.provider.infra.system.config.task;

import com.alibaba.fastjson.JSONObject;
import com.sailors.common.task.provider.domian.service.impl.FileTaskService;
import com.sailors.common.task.provider.faced.model.enums.TaskDelayedLevelEnum;
import com.sailors.common.task.provider.infra.design.common.enums.BussinessBaseEnumUtil;
import com.sailors.common.task.provider.infra.repository.IFileTaskLogRepository;
import com.sailors.common.task.provider.infra.repository.model.FileTaskLogPo;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.DelayQueue;

/**
 * Delayed file init runner
 *
 * @description: 重启后恢复定时任务
 * @author: cyj
 * @date 2022 -11-23 15:41:14
 */
@Component
@Slf4j
public class DelayedFileInitRunner implements InitializingBean {

    /**
     * Delay queue tasks
     */
    @Autowired
    @Qualifier("fileTaskDelayQueue")
    public DelayQueue<CommonDelayQueueTask<Long>> delayQueueTasks;

    /**
     * File task log repository
     */
    @Autowired
    public IFileTaskLogRepository fileTaskLogRepository;

    /**
     * File task service
     */
    @Autowired
    private FileTaskService fileTaskService;

    @Override
    public void afterPropertiesSet() {
        List<FileTaskLogPo> needDelayed = fileTaskLogRepository.getAllNeedDelayed();
        needDelayed.stream().forEach(fileTaskLogPo -> {
            TaskDelayedLevelEnum taskDelayedLevelEnum = BussinessBaseEnumUtil.getByCode(fileTaskLogPo.getDelayedCheck(), TaskDelayedLevelEnum.class);
            delayQueueTasks.add(new CommonDelayQueueTask<Long>(fileTaskLogPo.getId(), taskDelayedLevelEnum.delayTime, (taskId) -> {
                fileTaskService.delayedFailed(taskId);
            }));
            log.info("补充定时任务到延时队列：{}", JSONObject.toJSON(fileTaskLogPo));
        });

    }
}
